import {getUserInfo,logout} from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import config from '@/config/index'
import { defineStore } from 'pinia'

const useUserStore = defineStore('user',{
  state: () => ({
    user: null,
    token:'',
    userInfo:null,
  }),
  actions: {
    setUserInfo(res){
      return new Promise((resolve, reject) => {
        this.user = res;
        this.token = res.session_key;
        setToken(res.session_key);
        getUserInfo().then( Response => {
          console.log(this.user)
          this.userInfo = Response.data;
          resolve(Response);
        }).catch(error => {
          reject(error)
        })
      }).catch(error => {
        reject(error)
      })
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo().then( res => {
          this.userInfo = res.data;
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // user logout
    logout() {
      return new Promise((resolve, reject) => {
        logout().then(res =>{
          removeToken();
          resolve();
        }).catch(error =>{
          //console.log(error)
          removeToken();
          reject();
        })
      })
    },
  }
})
export default useUserStore